import flow from '@/api/flow'
const {getTaskInfo, getCandidatesListByTaskId} = flow
import { uniqueArrayObject } from '@/utils'
export default {
  data() {
    return {
      extraField: {},
    }
  },
  watch: {
    tableData(val) {
      if(val&&val.length > 0&&this.activeName === 'request'){
        this.loadTaskInfo(val)
      }
    },
  },
  methods: {
    loadTaskInfo(rows, key = 'id') {
      //草稿、结束、人工结束状态不显示审批人、当前节点(没有)
      const unLoadStatus = ['draft', 'end', 'manualend']
      const ids = rows
        .filter((item) => !unLoadStatus.includes(item.status)).map((item) => item[key])
      if (ids.length !== 0) {
        getTaskInfo(ids).then((resp) => {
          const data = resp.value
          for (let key in data) {
            if (!this.extraField[key]) {
              this.$set(this.extraField, key, {})
            }
            this.setTaskInfo(key, data[key])
          }
        })
      }
    },
    async setTaskInfo(id, tasks) {
      if (tasks&&tasks.length < 1) return
      const taskNames = tasks.map((item) => item.name).unique()
      this.$set(this.extraField[id], 'nodeName', taskNames)
      this.$set(this.extraField[id], 'taskId', tasks[0].taskId)
      let assignee = []
      let promises = []

      tasks.forEach((item) => {
        promises.push(this.getAssigneeUser(item))
      })
      Promise.all(promises).then((resultArr) => {
        resultArr.forEach((item) => {
          assignee = assignee.concat(item)
        })
        this.$set(
          this.extraField[id],
          'nodeApprover',
          uniqueArrayObject(assignee, 'id')
        )
      })
    },
    //获取任务的审批人，返回promise，如果候选人有多个，就要调接口取出来
    getAssigneeUser(task) {
      return new Promise((resolve, reject) => {
        if (task.assigneeId === '0') {
          getCandidatesListByTaskId(task.id).then((response) => {
            resolve(response)
          })
        } else {
          resolve([
            {
              type: 'user',
              name: task.assigneeName,
              id: task.assigneeId,
            },
          ])
        }
      })
    },
  },
}
